package perf.parse.valgrind;

import java.util.HashMap;

public class Decompressor {

	private HashMap<Integer, String> lookup = new HashMap<Integer, String>();

	public int getInt( String num, int base ) {
		char c = num.charAt(0);
		int i;
		
		if ( c == '+' ) {
			i = base + Integer.parseInt( num.substring( 1 ) );
		} else if ( c == '-' ) {
			i = base - Integer.parseInt( num.substring( 1 ) );	
		} else if ( c == '*' ) {
			i = base;
		} else {
			i = Integer.parseInt( num );
		}
		return i;
	}

	public String getVal( String all, int pos ) {
		Integer num;
		String val = all.substring( pos );
		//check if string compression is used
		if ( val.charAt(0) == '(' ) {
			int idx = val.indexOf(')', 1);
			try {
				num = Integer.parseInt( val.substring( 1, idx ) );
			} catch (NumberFormatException nfe ) {
				if ( val.substring( 1, idx ).equals( "below main" ) ) {
					return "below main";
				} else {
					throw nfe;
				}
			}
			
 			//if the string is longer than the end parentheses
			//then it is defining a value
			if ( val.length() > idx + 1 ) {
				return addVal( num, val.substring( idx + 2 ) );
			} else {
				return lookupVal( num );
			}
		}
		return val;
	}
	
	private String addVal( Integer key, String val ) {
		lookup.put( key, val );
		return val;
	}
	
	private String lookupVal( Integer key ) {
		if ( lookup.containsKey( key ) ) {
			return lookup.get( key );
		} else {
			throw new RuntimeException( "No value has been defined for the key: " + key );
		}
	}

}
